<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb :separator-icon="ArrowRight" class="bread-crumb">
      <el-breadcrumb-item :to="{ path: '/' }">
        <el-icon><HomeFilled /></el-icon>
        首页
      </el-breadcrumb-item>
      <el-breadcrumb-item>我的购物车</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="cart-container">
      <div class="cart-header">
        <h3 class="cart-title">我的购物车</h3>
        <div class="cart-desc">查看购物车清单</div>
      </div>
      <div class="cart-list">
        <el-table :data="list" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column label="商品" width="450">
            <template #default="scope">
              <div class="order-item">
                <img :src="scope.row.skuPic" alt="" class="img" />
                <div class="order-info">
                  <div class="title">{{ scope.row.title }}</div>
                  <div
                    class="attr"
                    v-for="item in scope.row.skuAttrsVals"
                    :key="item.attrId"
                  >
                    {{ item.attrName }}：{{ item.attrValue }}
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="单价(元)" align="center">
            <template #default="scope">
              <span class="red" style="font-size: 14px; font-weight: 300">{{
                scope.row.price
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="数量" align="center">
            <template #default="scope">
              <el-input-number
                @change="updateProductCount(scope.row)"
                v-model="scope.row.count"
                :min="1"
                :step="1"
              />
            </template>
          </el-table-column>
          <el-table-column label="小计(元)" align="center">
            <template #default="scope">
              <span class="red" style="font-size: 16px; font-weight: 300">{{
                scope.row.totalPrice
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <div class="action">
                <el-button
                  link
                  type="success"
                  size="small"
                  @click="addCollect(scope.row)"
                  >加入收藏夹</el-button
                >
                <el-button link size="small" @click="handlerDelete(scope.row)"
                  >删除</el-button
                >
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="purchase">
        <span class="pur-text">
          商品总价(不含运费) <span class="red">{{ totalAmount }}</span
          >元
        </span>
        <el-button color="rgb(220 38 38)" @click="goPurchase"
          >确认订单</el-button
        >
      </div>
    </div>
  </div>
</template>
<script setup>
import { getCurrentInstance, ref, watch } from "vue";
import { Decimal } from "decimal.js";
import {
  getUserCart,
  updateCountItem,
  removeItem,
  selectCartProduct,
} from "@/api/mall/client/cart/cart";
import { useRouter } from "vue-router";
const { proxy } = getCurrentInstance();
import useCartStore from "@/store/modules/cart";
import { addCollectSpu, delCollectSpu } from "@/api/mall/client/user/collect";
const cartStore = useCartStore();
const router = useRouter();
const cartInfo = ref({
  countNum: 0,
  countType: 0,
  reduce: null,
  totalAmount: 0,
  list: [],
});
const list = ref([]);
const getCartList = async () => {
  const res = await getUserCart();
  cartInfo.value = res.data;
  list.value = res.data.items;
};
// 删除某一项商品
const handlerDelete = (item) => {
  proxy.$modal.confirm("是否删除该商品？").then((res) => {
    removeItem({ skuId: item.skuId, num: item.count }).then((res) => {
      getCartList();
    });
  });
};
// 修改商品数量
const updateProductCount = async (item) => {
  const res = await updateCountItem({ skuId: item.skuId, num: item.count });
  // 重新计算价格
  calRowTotalPrice(item);
  calTotalAmount();
};
// 计算一行的小计价格
const calRowTotalPrice = (row) => {
  console.log(row);
  row.totalPrice = Decimal.mul(row.price, row.count);
};
// 统计购物车总价格
const totalAmount = ref(0);
const calTotalAmount = () => {
  totalAmount.value = 0;
  list.value.forEach((item) => {
    if (ids.value.includes(item.skuId)) {
      totalAmount.value = new Decimal(totalAmount.value).plus(item.totalPrice);
    }
  });
};
// 多选
const ids = ref([]);
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.skuId);
  const promises = [];
  calTotalAmount();
  list.value.forEach((item) => {
    if (ids.value.includes(item.skuId)) {
      promises.push(selectProduct(item.skuId, 1));
    } else {
      promises.push(selectProduct(item.skuId, 0));
    }
  });
  Promise.all(promises).then((res) => {
    // 不能调用，会刷新数据，价格只能前端计算
    // getCartList();
  });
};
// 选中
const selectProduct = async (id, checked) => {
  const res = await selectCartProduct({ skuId: id, checked: checked });
};
// 监听ids
watch(
  () => ids.value,
  (val) => {}
);
// 跳转确认订单
const goPurchase = () => {
  if (ids.value.length <= 0) {
    return;
  }
  router.push({
    path: "/purchase",
  });
};
// 加入收藏夹
const addCollect = async (row) => {
  await addCollectSpu({ spuId: row.spuId });
  proxy.$modal.msgSuccess("收藏成功");
};
getCartList();
</script>

<style lang="scss" scoped>
:deep(.el-checkbox__inner) {
  &:hover {
    border-color: #1aa684;
  }
}
:deep(.el-checkbox__input.is-checked) {
  border-color: #1aa684;
  background-color: #1aa684;
}
:deep(.el-checkbox__input.is-checked) {
  .el-checkbox__inner {
    border-color: #1aa684;
    background-color: #1aa684;
  }

  // background-color: #1aa684;
}
.bread-crumb {
  padding: 20px 0;
  --el-color-primary: #1aa684;
}
// :deep(.el-breadcrumb__inner a:hover, .el-breadcrumb__inner.is-link:hover) {
//   color: #1aa684;
// }

.cart-container {
  background: #fff;
  padding: 20px;

  .cart-title {
    color: #555;
    font-size: 22px;
    font-weight: 300;
  }
  .cart-desc {
    font-size: 14px;
    color: #aaa;
  }
  .cart-list {
    margin-top: 20px;
    margin-bottom: 10px;
    .action {
      display: flex;
      flex-direction: column;
      align-items: start;
      .el-button {
        margin-left: 0;
      }
    }
    .el-input-number {
      width: 120px;
      :deep(.is-focus) {
        box-shadow: 0 0 0 1px #1aa684 inset;
      }
      :deep(.el-input-number__decrease) {
        &:hover {
          color: #1aa684;
        }
      }
      :deep(.el-input-number__increase) {
        &:hover {
          color: #1aa684;
        }
      }
    }
    .order-item {
      display: flex;
      .img {
        width: 60px;
        height: 60px;
        object-fit: cover;
        margin-right: 20px;
      }
      .order-info {
        .title {
          color: #333;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        .attr {
          color: #999;
        }
      }
    }
  }
  .purchase {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    .pur-text {
      font-size: 13px;
      margin-right: 5px;
      .red {
        margin-left: 5px;
        margin-right: 3px;
        font-weight: 300;
      }
    }
  }
}
</style>
